package com.starblink.android.basic.ext

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.widget.rv.WrapStaggeredGridLayoutManager
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor


/**
 * 绑定设置商品双列feeds样式
 * 瀑布流不要刷新Adapter全部，以免出现重排，尽量使用[RecyclerView.Adapter.notifyItemRangeChanged]
 */
fun RecyclerView.bindProductFeeds(
    adapter: RecyclerView.Adapter<*>,
    spanCount: Int = 2,
    horGap: Int = 11,
    verGap: Int = 12,
    withEdge: Boolean = true,
    scrollStateChange: ((state: Int) -> Unit)? = null,
    onVerticalScroll: ((totalScrolled: Int) -> Unit)? = null,
): RecyclerView.LayoutManager {

    setItemViewCacheSize(10)
    isNestedScrollingEnabled = true

    val staggered =
        WrapStaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL).apply {
            gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        }
    layoutManager = staggered
    this.adapter = adapter

//    itemAnimator = null

    var hasGap = false
    repeat(itemDecorationCount) {
        if (getItemDecorationAt(it) is SimpleGapItemDecor) {
            hasGap = true
        }
    }
    if (!hasGap) {
        addItemDecoration(
            SimpleGapItemDecor(
                horGap = horGap.dp2px(),
                verGap = verGap.dp2px(),
                withEdge = withEdge
            )
        )
    }

    addOnScrollListener(object : RecyclerView.OnScrollListener() {

        var scrolled: Int = 0

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            scrolled += dy
            onVerticalScroll?.invoke(scrolled)
        }

        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            scrollStateChange?.invoke(newState)
        }

    })

    return staggered
//    var checkGapMethod: Method? = null
//    var decorationMethod: Method? = null
//    try {
//        checkGapMethod = staggered.javaClass.getDeclaredMethod("checkForGaps").apply {
//            isAccessible = true
//        }
//        decorationMethod = this.javaClass.getDeclaredMethod("markItemDecorInsetsDirty").apply {
//            isAccessible = true
//        }
//    } catch (e: Exception) {
//        e.printStackTrace()
//    }
//
//    addOnScrollListener(object : RecyclerView.OnScrollListener() {
//
//        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
//            super.onScrollStateChanged(recyclerView, newState)
//            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                staggered.invalidateSpanAssignments()
//                if (checkGapMethod?.invoke(staggered) == true) {
//                    decorationMethod?.invoke(this@bindProductFeeds)
//                }
//            }
//        }
//
//    })

}

/**
 * 监听横向 RecyclerView 是否到达底部
 */
fun RecyclerView.isHorizontalSlideToBottom(isBottom: () -> Unit, isNotBottom: () -> Unit) {
    addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            if (recyclerView.computeHorizontalScrollExtent() + recyclerView.computeHorizontalScrollOffset()
                >= recyclerView.computeHorizontalScrollRange()
            ) {
                isBottom.invoke()
            } else {
                isNotBottom.invoke()
            }
        }
    })
}

fun View.staggerFullSpan(full: Boolean = true) {
    val layoutParams = layoutParams
    if (layoutParams is StaggeredGridLayoutManager.LayoutParams) {
        if (full != layoutParams.isFullSpan) {
            layoutParams.isFullSpan = true
            this.layoutParams = layoutParams
        }
    }
}

//停止惯性滚动
fun RecyclerView.stopInertiaRolling() {
    try {
        //如果是Support的RecyclerView则需要使用"cancelTouch"
        val field = this.javaClass.getDeclaredMethod("cancelScroll")
        field.isAccessible = true
        field.invoke(this)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}